﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;

namespace ExaminationSys.View.SystemManage
{
    public partial class DBSubjectEdit : System.Web.UI.UserControl
    {
        private static readonly DBSubjectService Proxy = ObjectFactory<DBSubjectService>.Create();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Bind();
            }
        }
        private void Bind()
        {
            // TO DO
        }

        public Store GridStore { get; set; }
        public string ID { get; set; }


        public void SetData(string id)
        {
            KeyWord.Text = "";
            Knowledge.Text = "";
            Stage.Text = "";
            SubjectType.Text = "";
            Challenge.Text = "";
            AttachFile.Text = "";
            Title.Text = "";
            Content.Text = "";
            chkLock.Checked = false;
            txtAttachFile.Value = "";
            txtSerialNo.Value = "";
            this.DBSubjectEditWindow.Title = "题库管理(大题)新增";
            Stage.Select(2);
            Challenge.Select(2);
            SubjectType.Select(0);
            if (!string.IsNullOrEmpty(id))
            {
                this.DBSubjectEditWindow.Title = "题库管理(大题)修改";
                var realId = new Guid(id);
                var dbsubject = Proxy.Get(realId);

                KeyWord.Text = dbsubject.KeyWord;
                Knowledge.Text = dbsubject.Knowledge;
                Stage.Text = dbsubject.Stage;
                SubjectType.Text = dbsubject.SubjectType;
                Challenge.Text = dbsubject.Challenge;
                AttachFile.Text = dbsubject.AttachFile;
                Title.Text = dbsubject.Title;
                Content.Text = dbsubject.Content;
                X.Js.Call("attachFile", dbsubject.AttachFile);
                X.Js.Call("serialNo", dbsubject.SerialNo);

                LockHidden.Value = dbsubject.Lock.ToString();
                chkLock.Checked = dbsubject.Lock;
                X.Js.Call("lock", dbsubject.Lock);

                ID = id;
                X.Js.Call("setID", id);
            }
        }

        public void Show()
        {
            this.DBSubjectEditWindow.Show();
        }

        protected void SaveDBSubject(object sender, DirectEventArgs e)
        {
            DBSubjectSave(0);
        }

        protected void SaveDBSubjectAndSubQuestion(object sender, DirectEventArgs e)
        {
            DBSubjectSave(1);
        }

        private void DBSubjectSave(int flag)
        {
            var keyword = KeyWord.Text.Trim();
            var knowledge = Knowledge.Text.Trim();
            var stage = Stage.Text.Trim();// 请选择类型
            var subjecttype = SubjectType.Text.Trim(); // 题型
            var challenge = Challenge.Text.Trim(); // 难度
            //var attachfile = AttachFile.FileName.Trim();
            var title = Title.Text.Trim();
            var content = Content.Text.Trim();
            var attachfile = txtAttachFile.Value;
            if (AttachFile.HasFile && subjecttype.Equals("视听"))
            {
                attachfile = this.AttachFile.PostedFile.FileName.ToString();
                string strFileName = Path.GetExtension(this.AttachFile.PostedFile.FileName).ToUpper();
                //获取文件后缀              
                if (!(strFileName == ".MP3" || strFileName == ".MP4" || strFileName == ".AVI"))
                {
                    MessageBoxHelper.ShowWarning("文件格式不正确！\r\n只能上传MP3、MP4、AVI 文件");
                    return;
                }

                int FileSize = Int32.Parse(this.AttachFile.PostedFile.ContentLength.ToString());
                if (FileSize > 30 * 1024 * 1024)
                {
                    MessageBoxHelper.ShowWarning("上传文件过大");
                    return;
                }

                var fileNameTmp = Path.GetFileName(this.AttachFile.PostedFile.FileName);
                string fileName = string.Format("{0}_{1}_{2}", Guid.NewGuid().ToString(), DateTime.Now.ToString("yyyyMMddHHmm"), fileNameTmp);
                var filePath = string.Format("{0}/DBSubject", UIHelpers.BasePath);
                string fileFullName = Path.Combine(Server.MapPath(filePath), fileName);

                try
                {
                    this.AttachFile.PostedFile.SaveAs(fileFullName);
                    attachfile = fileName;
                    txtAttachFile.Value = fileName;
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowError("附件上传出错", ex.Message);
                    return;
                }
            }
            else if (!subjecttype.Equals("视听"))
                attachfile = string.Empty;
            

            #region 条件

            if (string.IsNullOrWhiteSpace(title))
            {
                MessageBoxHelper.ShowWarning("标题不能为空");
                return;
            }
            //if (string.IsNullOrWhiteSpace(keyword))
            //{
            //    MessageBoxHelper.ShowWarning("关键字不能为空");
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(knowledge))
            //{
            //    MessageBoxHelper.ShowWarning("知识点不能为空");
            //    return;
            //}
            if (string.IsNullOrEmpty(stage))
            {
                MessageBoxHelper.ShowWarning("阶段不能为空");
                return;
            }
            if (string.IsNullOrEmpty(subjecttype))
            {
                MessageBoxHelper.ShowWarning("题型不能为空");
                return;
            }
            if (string.IsNullOrEmpty(challenge))
            {
                MessageBoxHelper.ShowWarning("难度不能为空");
                return;
            }
            if (string.IsNullOrEmpty(content))
            {
                MessageBoxHelper.ShowWarning("内容不能为空");
                return;
            }
            if (subjecttype.Equals("视听") && string.IsNullOrEmpty(attachfile))
            {
                MessageBoxHelper.ShowWarning("视听题，视听附件不能为空");
                return;
            }
            #endregion

            var id = DBSubjectIDHidden.Value;
            var actionflag = string.IsNullOrWhiteSpace(id);
            Guid realId = string.IsNullOrEmpty(id) ? Guid.NewGuid() : new Guid(id);

            ExaminationSys.DataAccess.Entity.DBSubject entity = new DataAccess.Entity.DBSubject();
            string headstr = System.DateTime.Now.ToString("yyyyMMdd");
            entity.ID = realId;
            entity.SerialNo = string.IsNullOrEmpty(txtSerialNo.Value) ? Proxy.GetSerialNo(headstr) : txtSerialNo.Value;
            entity.KeyWord = keyword;
            entity.Knowledge = knowledge;
            entity.Stage = stage;
            entity.SubjectType = subjecttype;
            entity.Challenge = challenge;
            entity.Title = title;
            entity.AttachFile = attachfile;
            entity.Content = content;

            entity.Status = 1;
            entity.AddTime = DateTime.Now;
            entity.Lock = chkLock.Checked;

            var op = FormsAuthenticationHelper.GetCurrentUserID();
            if (string.IsNullOrEmpty(op))
            {
                FormsAuthenticationHelper.SignOut();
                Response.Redirect("~/Account/Login.aspx");
            }
            entity.Operator = op;

            entity.OperatorTime = DateTime.Now;


            var sucess = false;

            if (actionflag)
            {
                entity.Point = 0;
                var retCode = Proxy.Insert(entity);
                sucess = retCode != null;
                realId = retCode;
            }
            else
            {
                sucess = Proxy.Update(entity);
            }

            if (sucess)
            {
                //MessageBoxHelper.ShowInfo("保存成功");
                GridStore.Reload();
                DBSubjectEditWindow.Hide();
                if (flag == 1)
                {
                    Response.Redirect("DBSubjectQuestionList.aspx?id=" + realId);
                }
            }
            else
            {
                MessageBoxHelper.ShowInfo("保存失败");
                return;
            }
        }
    }
}